/**
 * 加密状态管理Store
 * 
 * @author RickPan Team
 * @version 1.0
 * @since 2025-07-19
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  MessageEncryption,
  KeyManager,
  EncryptionStatus,
  EncryptionErrorType,
  type EncryptionConfig,
  type EncryptionError,
  type EncryptionHealthStatus,
  type KeyCacheStats,
  type EncryptedMessage,
  type TeamKeyInfo
} from '@/utils/encryption'

export const useEncryptionStore = defineStore('encryption', () => {
  // ==================== 状态定义 ====================
  
  /** 加密配置 */
  const config = ref<EncryptionConfig>({
    enabled: true,
    algorithm: 'AES-256-GCM',
    keyLength: 256,
    ivLength: 12,
    tagLength: 128,
    cacheTTL: 30 * 60 * 1000, // 30分钟
    maxCacheSize: 50,
    autoPreloadKeys: true,
    performanceMonitoring: false
  })

  /** 是否支持Web Crypto API */
  const isSupported = ref<boolean>(MessageEncryption.isSupported())

  /** 加密服务健康状态 */
  const healthStatus = ref<EncryptionHealthStatus>({
    healthy: false,
    algorithm: 'unknown',
    checkTime: 0
  })

  /** 密钥管理器实例 */
  const keyManager = KeyManager.getInstance()

  /** 当前正在处理的加密任务 */
  const encryptionTasks = ref<Map<string, EncryptionStatus>>(new Map())

  /** 错误日志 */
  const errorLog = ref<EncryptionError[]>([])

  /** 性能统计 */
  const performanceStats = ref({
    totalEncryptions: 0,
    totalDecryptions: 0,
    avgEncryptTime: 0,
    avgDecryptTime: 0,
    lastPerformanceTest: 0
  })

  // ==================== 计算属性 ====================

  /** 是否可用（支持且启用） */
  const isAvailable = computed(() => isSupported.value && config.value.enabled)

  /** 是否健康 */
  const isHealthy = computed(() => healthStatus.value.healthy)

  /** 活跃任务数量 */
  const activeTaskCount = computed(() => {
    let count = 0
    for (const status of encryptionTasks.value.values()) {
      if (status === EncryptionStatus.ENCRYPTING || status === EncryptionStatus.DECRYPTING) {
        count++
      }
    }
    return count
  })

  /** 最近的错误 */
  const recentErrors = computed(() => {
    const oneHourAgo = Date.now() - 60 * 60 * 1000
    return errorLog.value.filter(error => error.timestamp > oneHourAgo)
  })

  // ==================== 核心方法 ====================

  /**
   * 初始化加密服务
   */
  async function initialize(): Promise<void> {
    try {
      console.log('🔐 初始化加密服务...')

      // 检查浏览器支持
      if (!MessageEncryption.isSupported()) {
        throw new Error('浏览器不支持Web Crypto API')
      }

      // 检查服务健康状态
      await checkHealth()

      console.log('✅ 加密服务初始化成功')
    } catch (error) {
      console.error('❌ 加密服务初始化失败:', error)
      logError({
        name: 'EncryptionInitError',
        message: error instanceof Error ? error.message : '初始化失败',
        type: EncryptionErrorType.BROWSER_NOT_SUPPORTED,
        timestamp: Date.now()
      } as EncryptionError)
      throw error
    }
  }

  /**
   * 检查加密服务健康状态
   */
  async function checkHealth(): Promise<EncryptionHealthStatus> {
    try {
      const status = await keyManager.checkEncryptionHealth()
      healthStatus.value = status
      return status
    } catch (error) {
      const errorStatus: EncryptionHealthStatus = {
        healthy: false,
        algorithm: 'unknown',
        checkTime: Date.now(),
        error: error instanceof Error ? error.message : '未知错误'
      }
      healthStatus.value = errorStatus
      return errorStatus
    }
  }

  /**
   * 获取团队密钥
   */
  async function getTeamKey(teamId: number, forceRefresh: boolean = false): Promise<string> {
    try {
      return await keyManager.getTeamKey(teamId, forceRefresh)
    } catch (error) {
      logError({
        name: 'KeyFetchError',
        message: error instanceof Error ? error.message : '获取密钥失败',
        type: EncryptionErrorType.KEY_FETCH_FAILED,
        teamId,
        timestamp: Date.now()
      } as EncryptionError)
      throw error
    }
  }

  /**
   * 加密消息
   */
  async function encryptMessage(
    content: string,
    teamId: number,
    taskId?: string
  ): Promise<EncryptedMessage> {
    const id = taskId || `encrypt_${Date.now()}_${Math.random()}`
    
    try {
      // 设置任务状态
      setTaskStatus(id, EncryptionStatus.ENCRYPTING)

      // 获取团队密钥
      const teamKey = await getTeamKey(teamId)

      // 执行加密
      const startTime = performance.now()
      const encrypted = await MessageEncryption.encryptMessage(content, teamKey)
      const endTime = performance.now()

      // 更新性能统计
      updatePerformanceStats('encrypt', endTime - startTime)

      // 设置完成状态
      setTaskStatus(id, EncryptionStatus.ENCRYPTED)

      return encrypted

    } catch (error) {
      setTaskStatus(id, EncryptionStatus.ENCRYPT_FAILED)
      logError({
        name: 'EncryptionError',
        message: error instanceof Error ? error.message : '加密失败',
        type: EncryptionErrorType.ENCRYPTION_FAILED,
        teamId,
        timestamp: Date.now()
      } as EncryptionError)
      throw error
    }
  }

  /**
   * 解密消息
   */
  async function decryptMessage(
    encryptedData: EncryptedMessage,
    teamId: number,
    taskId?: string
  ): Promise<string> {
    const id = taskId || `decrypt_${Date.now()}_${Math.random()}`
    
    try {
      // 设置任务状态
      setTaskStatus(id, EncryptionStatus.DECRYPTING)

      // 获取团队密钥
      const teamKey = await getTeamKey(teamId)

      // 执行解密
      const startTime = performance.now()
      const decrypted = await MessageEncryption.decryptMessage(encryptedData, teamKey)
      const endTime = performance.now()

      // 更新性能统计
      updatePerformanceStats('decrypt', endTime - startTime)

      // 设置完成状态
      setTaskStatus(id, EncryptionStatus.DECRYPTED)

      return decrypted

    } catch (error) {
      setTaskStatus(id, EncryptionStatus.DECRYPT_FAILED)
      logError({
        name: 'DecryptionError',
        message: error instanceof Error ? error.message : '解密失败',
        type: EncryptionErrorType.DECRYPTION_FAILED,
        teamId,
        timestamp: Date.now()
      } as EncryptionError)
      throw error
    }
  }

  /**
   * 批量加密多个字段
   */
  async function encryptMultipleFields(
    data: { content?: string; fileName?: string },
    teamId: number
  ): Promise<{ encryptedContent?: EncryptedMessage; encryptedFileName?: EncryptedMessage }> {
    try {
      const teamKey = await getTeamKey(teamId)
      return await MessageEncryption.encryptMultipleFields(data, teamKey)
    } catch (error) {
      logError({
        name: 'BatchEncryptionError',
        message: error instanceof Error ? error.message : '批量加密失败',
        type: EncryptionErrorType.ENCRYPTION_FAILED,
        teamId,
        timestamp: Date.now()
      } as EncryptionError)
      throw error
    }
  }

  /**
   * 批量解密多个字段
   */
  async function decryptMultipleFields(
    encryptedData: { encryptedContent?: EncryptedMessage; encryptedFileName?: EncryptedMessage },
    teamId: number
  ): Promise<{ content?: string; fileName?: string }> {
    try {
      const teamKey = await getTeamKey(teamId)
      return await MessageEncryption.decryptMultipleFields(encryptedData, teamKey)
    } catch (error) {
      logError({
        name: 'BatchDecryptionError',
        message: error instanceof Error ? error.message : '批量解密失败',
        type: EncryptionErrorType.DECRYPTION_FAILED,
        teamId,
        timestamp: Date.now()
      } as EncryptionError)
      throw error
    }
  }

  /**
   * 预加载团队密钥
   */
  async function preloadTeamKeys(teamIds: number[]): Promise<void> {
    if (!config.value.autoPreloadKeys) {
      return
    }

    try {
      await keyManager.preloadTeamKeys(teamIds)
    } catch (error) {
      console.warn('⚠️ 预加载团队密钥失败:', error)
    }
  }

  /**
   * 轮换团队密钥
   */
  async function rotateTeamKey(teamId: number): Promise<string> {
    try {
      return await keyManager.rotateTeamKey(teamId)
    } catch (error) {
      logError({
        name: 'KeyRotationError',
        message: error instanceof Error ? error.message : '密钥轮换失败',
        type: EncryptionErrorType.KEY_FETCH_FAILED,
        teamId,
        timestamp: Date.now()
      } as EncryptionError)
      throw error
    }
  }

  // ==================== 辅助方法 ====================

  /**
   * 设置任务状态
   */
  function setTaskStatus(taskId: string, status: EncryptionStatus): void {
    encryptionTasks.value.set(taskId, status)
  }

  /**
   * 获取任务状态
   */
  function getTaskStatus(taskId: string): EncryptionStatus | undefined {
    return encryptionTasks.value.get(taskId)
  }

  /**
   * 清理完成的任务
   */
  function cleanupCompletedTasks(): void {
    const completedStatuses = [
      EncryptionStatus.ENCRYPTED,
      EncryptionStatus.DECRYPTED,
      EncryptionStatus.ENCRYPT_FAILED,
      EncryptionStatus.DECRYPT_FAILED
    ]

    for (const [taskId, status] of encryptionTasks.value.entries()) {
      if (completedStatuses.includes(status)) {
        encryptionTasks.value.delete(taskId)
      }
    }
  }

  /**
   * 记录错误
   */
  function logError(error: EncryptionError): void {
    errorLog.value.push(error)
    
    // 保持错误日志在合理大小
    if (errorLog.value.length > 100) {
      errorLog.value = errorLog.value.slice(-50)
    }
  }

  /**
   * 更新性能统计
   */
  function updatePerformanceStats(operation: 'encrypt' | 'decrypt', duration: number): void {
    if (!config.value.performanceMonitoring) {
      return
    }

    if (operation === 'encrypt') {
      performanceStats.value.totalEncryptions++
      performanceStats.value.avgEncryptTime = 
        (performanceStats.value.avgEncryptTime * (performanceStats.value.totalEncryptions - 1) + duration) / 
        performanceStats.value.totalEncryptions
    } else {
      performanceStats.value.totalDecryptions++
      performanceStats.value.avgDecryptTime = 
        (performanceStats.value.avgDecryptTime * (performanceStats.value.totalDecryptions - 1) + duration) / 
        performanceStats.value.totalDecryptions
    }
  }

  /**
   * 获取缓存统计
   */
  function getCacheStats(): KeyCacheStats {
    return keyManager.getCacheStats()
  }

  /**
   * 清空密钥缓存
   */
  function clearKeyCache(teamId?: number): void {
    if (teamId) {
      keyManager.clearTeamKeyCache(teamId)
    } else {
      keyManager.clearAllKeyCache()
    }
  }

  /**
   * 更新配置
   */
  function updateConfig(newConfig: Partial<EncryptionConfig>): void {
    config.value = { ...config.value, ...newConfig }
  }

  /**
   * 重置错误日志
   */
  function clearErrorLog(): void {
    errorLog.value = []
  }

  /**
   * 重置性能统计
   */
  function resetPerformanceStats(): void {
    performanceStats.value = {
      totalEncryptions: 0,
      totalDecryptions: 0,
      avgEncryptTime: 0,
      avgDecryptTime: 0,
      lastPerformanceTest: 0
    }
  }

  return {
    // 状态
    config,
    isSupported,
    healthStatus,
    encryptionTasks,
    errorLog,
    performanceStats,

    // 计算属性
    isAvailable,
    isHealthy,
    activeTaskCount,
    recentErrors,

    // 方法
    initialize,
    checkHealth,
    getTeamKey,
    encryptMessage,
    decryptMessage,
    encryptMultipleFields,
    decryptMultipleFields,
    preloadTeamKeys,
    rotateTeamKey,
    setTaskStatus,
    getTaskStatus,
    cleanupCompletedTasks,
    getCacheStats,
    clearKeyCache,
    updateConfig,
    clearErrorLog,
    resetPerformanceStats
  }
})
